package com.jeeinc.oa.controller;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeeinc.oa.domain.Account;
import com.jeeinc.oa.service.IAccountService;
import com.jeeinc.oa.utils.AccountUtils;
import com.jeeinc.oa.utils.StringUtils;

@Controller
@RequestMapping(value = "/system/")
public class AccountController {
	@Resource
	private IAccountService accountService;
	
	@RequestMapping(value = "login")
	public String login(Model model , HttpServletRequest request, String username, String password) {
		Account account = accountService.getAccount(username);
		
		if (account == null) {
			model.addAttribute("message", "不存在的用户");
			return "login";
		}
		
		if (account.getState() == Account.ACCOUNT_STATE_CANCEL) {
			model.addAttribute("message", "该用户已注销,请联系管理员");
			return "login";
		}
		
		if (account.getState() == Account.ACCOUNT_STATE_PAUSE) {
			model.addAttribute("message", "该用户已暂停使用,请联系管理员");
			return "login";
		}
		
		if (account.getState() == Account.ACCOUNT_STATE_FROZEN) {
			model.addAttribute("message", "该用户已被冻结,请联系管理员");
			return "login";
		}
		
		if (!StringUtils.encryption(password, account.getMask()).equals(account.getLoginpwd())) {
			account.setLoginfail(account.getLoginfail() + 1);
			if (account.getLoginfail() >= account.getMaxfail()) {
				account.setState(Account.ACCOUNT_STATE_PAUSE);
				model.addAttribute("message", "由于你多次输入错误,系统将暂停该账号");
			} else {
				model.addAttribute("message", "用户名或密码错误,再错误输入" + (account.getMaxfail() - account.getLoginfail()) + "后账号将被暂停使用");
			}
			accountService.updateAccount(account);
			return "login";
		}
		
		account.setLastlogin(new Date());
		account.setLoginfail(0);
		accountService.updateAccount(account);
		AccountUtils.setAccount(request.getSession(), account);
		return "redirect:/admin";
	}
	
	@RequestMapping(value = "logout")
	public void logout(HttpServletRequest request , HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.invalidate();
		try {
			response.sendRedirect("../");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
